package chapter9;

/**
 * Created by LinGer on 2019/6/18
 */
public class InterruptTest extends Thread{

    public InterruptTest(String name){
        super(name);
    }

    @Override
    public void run() {
        try {
            int i = 0;
            while (!isInterrupted()){
                i++;
                System.out.println(this.getName() + " state: " + this.getState() + " loop " + i);
                Thread.sleep(100);
            }
        } catch (InterruptedException e) {
            System.out.println(this.getName() + " state: [" + this.getState() + "] catch exception");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        try {
            Thread t1 = new InterruptTest("t1");
            System.out.println(t1.getName() + " [" + t1.getState() + "] 1");
            t1.start();
            System.out.println(t1.getName() + " [" + t1.getState() + "] 2");

            //主线程休眠300ms，然后给t1发送中断指令
            Thread.sleep(300);
            t1.interrupt();
            System.out.println(t1.getName() + " [" + t1.getState() + "] 3");

            //主线程休眠3s，然后查看t1的状态
            Thread.sleep(3000);
            System.out.println(t1.getName() + " [" + t1.getState() + "] 4");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
